package com.mobileserver.servlet;

import com.google.protobuf.ByteString;
import com.hymane.materialhome.MaterialMessage;
import com.mobileserver.util.RedisUtil;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by xueal on 2017/9/18.
 */
@WebServlet(name = "BookListServlet")
public class BookListServlet extends HttpServlet {
    public static String bookListKey = "BookList";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("charset=UTF-8");
//            int len = request.getContentLength();
        ServletInputStream servletInputStream = request.getInputStream();
//        byte[] bytesRecv = new byte[len];
//        int readlen = servletInputStream.read(bytesRecv, 0, len);   // 第一次只能读取2920个字节！！！！！！
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buff[] = new byte[1024];
        int read;
        while ((read = servletInputStream.read(buff)) > 0) {
            baos.write(buff, 0, read);
        }
        byte[] bytesRecv = baos.toByteArray();

        getFile(bytesRecv, "E:\\files", "recv_buffer");

        MaterialMessage.TransPackage transPackage = MaterialMessage.TransPackage.parseFrom(bytesRecv);
        if (transPackage.getId() == MaterialMessage.TransPackage.PackageId.SaveBookList) {
            byte[] book = transPackage.getPackage().toByteArray();
//                 getFile(book, "E:\\files", "booklist_save");
            Jedis jedis = RedisUtil.getJedis();
            jedis.set(bookListKey.getBytes(), book);
        } else if (transPackage.getId() == MaterialMessage.TransPackage.PackageId.LoadBookList) {
            Jedis jedis = RedisUtil.getJedis();
            byte[] bytesBookList = jedis.get(bookListKey.getBytes());
//            getFile(bytesBookList, "E:\\files\\", "booklist_load");
            MaterialMessage.TransPackage.Builder builder = MaterialMessage.TransPackage.newBuilder();
            builder.setId(MaterialMessage.TransPackage.PackageId.LoadBookList);
            builder.setPackage(ByteString.copyFrom(bytesBookList));

            response.getOutputStream().write(bytesBookList);
//            List<String> bookList = jedis.lrange(bookListKey, 0, -1);
//            if (bookList.size() > 0) {
////            PrintWriter out = response.getWriter();
////            out.print(bookList.get(0));
//                byte[] _byte = bookList.get(0).getBytes("UTF-8");
//
//                String _str = new String(_byte, "UTF-8");
//
//                response.getOutputStream().write(_byte);
//            }
        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    /**
     * 根据byte数组，生成文件
     */
    public static void getFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
